<template>
  <a-button v-bind="attrs"><slot /></a-button>
</template>

<script>
import { debounce } from 'lodash-es';
export default {
  name: 'SpinButton',
  props: {
    spinHandle: { type: Array, default: () => ['click', 'dblclick'] },
  },
  data() {
    return {
      spinning: false,
    };
  },
  computed: {
    attrs() {
      const spinHandle = this.spinHandle.filter(Boolean);
      const attrs = spinHandle.reduce((res, key) => {
        return Object.assign(res, { [key]: this.agentHandle });
      }, {});
      return Object.assign({}, this.$attrs, attrs, { loading: this.spinning });
    },
  },
  methods: {
    agentHandle: debounce(async function (e) {
      const type = String(e.type).replace(/^[a-z]/i, ($0) => {
        return $0.toLocaleUpperCase();
      });
      const eventName = 'on' + type;
      if (typeof this.$attrs[eventName] === 'function') {
        this.spinning = true;
        const res = this.$attrs[eventName](e);
        if (res instanceof Promise) {
          await res.catch(() => {});
        }
        this.spinning = false;
      }
    }, 300),
  },
};
</script>

<style lang="less"></style>
